#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 12 14:12:48 2022

@author: mac1444
"""

import numpy as np
import matplotlib.pyplot as plt
class SimpleLinearRegression1:
    def __init__(self):
        # 初始化Simple Linear Regression 模型
        self.a_ = None
        self.b_ = None

    def fit(self, x_train, y_train):
        # 根据训练集x_train，y_train 训练Simple Linear Regression 模型
        assert x_train.ndim == 1, \
            "Simple Linear Regression can only solve simple feature training data"
        assert len(x_train) == len(y_train), \
            "the size of x_train must be equal to the size of y_train"
        # 求均值
        x_mean = x_train.mean()
        y_mean = y_train.mean()
        # 分子
        num = 0.0
        # 分母
        d = 0.0
        # 计算分子分母
        for x_i, y_i in zip(x_train, y_train):
            num += (x_i - x_mean) * (y_i - y_mean)
            d += (x_i - x_mean) ** 2
        # 计算参数a和b
        self.a_ = num / d
        self.b_ = y_mean - self.a_ * x_mean
        return self

    def predict(self, x_predict):
        # 给定待预测集x_predict，返回x_predict对应的预测结果值
        assert x_predict.ndim == 1, \
            "Simple Linear Regression can only solve simple feature training data"
        assert self.a_ is not None and self.b_ is not None, \
            "must fit before predict!"
        return np.array([self._predict(x) for x in x_predict])

    def _predict(self, x_single):
        # 给定单个待预测数据x_single，返回x_single对应的预测结果值
        return self.a_ * x_single + self.b_

    def __repr__(self):
        return "SimpleLinearRegression1()"

x = np.array([1, 3, 2, 1, 3])
y = np.array([14, 24, 18, 17, 27])
reg1 = SimpleLinearRegression1()
reg1.fit(x, y)
x_predict = 2
# x_predict = 2
y_predict = reg1.a_ * x_predict + reg1.b_
plt.scatter(x_predict, y_predict, c='g')
# reg1.predict(np.array([x_predict]))#单值预测
# print(reg1.a_)
# print(reg1.b_)
y_hat1 = reg1.predict(x)  # 产生多个预测值
plt.scatter(x, y)
plt.plot(x, y_hat1, color='r')
plt.axis([0, 4, 0, 28])
plt.show()